<template>
  <div class="app">
      <Unlock 
        v-if="showUnlock" 
        @open-player="showPlayer"
        :is-electron="isElectron"
        :is-maximized="isMaximized"
        @window-minimize="handleMinimize"
        @window-maximize="handleMaximize"
        @window-close="handleClose"
      />
    <Player 
      v-else 
      @open-unlock="showUnlockView"
      :is-electron="isElectron"
      :is-maximized="isMaximized"
      @window-minimize="handleMinimize"
      @window-maximize="handleMaximize"
      @window-close="handleClose"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import Unlock from './components/Unlock.vue'
import Player from './components/Player.vue'
import { storage } from './utils/storage.js'

const showUnlock = ref(true)
const isElectron = ref(false)
const isMaximized = ref(false)
let checkMaximizedInterval = null

onMounted(async () => {
  // 立即检查 window.electronAPI
  console.log('[App] onMounted - checking window.electronAPI:', {
    exists: typeof window.electronAPI !== 'undefined',
    hasWindow: typeof window.electronAPI?.window !== 'undefined',
    hasStorage: typeof window.electronAPI?.storage !== 'undefined',
    electronAPI: window.electronAPI
  })
  
  // 等待 window.electronAPI 初始化
  let retries = 0
  const maxRetries = 20
  
  const checkElectronAPI = () => {
    if (window.electronAPI && window.electronAPI.window) {
      isElectron.value = true
      console.log('[App] window.electronAPI found:', {
        hasWindow: !!window.electronAPI.window,
        hasStorage: !!window.electronAPI.storage,
        windowMethods: Object.keys(window.electronAPI.window || {}),
        window: window.electronAPI.window
      })
      // 检查窗口状态
      checkMaximized()
      // 定期检查窗口状态（用于响应外部最大化/还原操作）
      checkMaximizedInterval = setInterval(async () => {
        await checkMaximized()
      }, 100)
    } else if (retries < maxRetries) {
      retries++
      console.log(`[App] window.electronAPI not ready, retry ${retries}/${maxRetries}`)
      setTimeout(checkElectronAPI, 100)
    } else {
      console.error('[App] window.electronAPI not found after retries', {
        electronAPI: window.electronAPI,
        window: window.electronAPI?.window
      })
    }
  }
  
  checkElectronAPI()
  
  // 检查解锁状态
  const result = await storage.get(['isUnlocked', 'unlockTime'])
  
  if (result.isUnlocked && result.unlockTime) {
    const elapsed = Date.now() - result.unlockTime
    const remaining = 12 * 60 * 60 * 1000 - elapsed
    
    if (remaining > 0) {
      showUnlock.value = false
    }
  }
  
  // 监听存储变化
  storage.onChanged((changes, namespace) => {
    if (namespace === 'local' && changes.isUnlocked) {
      if (changes.isUnlocked.newValue) {
        showUnlock.value = false
      } else {
        showUnlock.value = true
      }
    }
  })
})

onUnmounted(() => {
  if (checkMaximizedInterval) {
    clearInterval(checkMaximizedInterval)
  }
})

// 窗口控制函数
async function checkMaximized() {
  if (window.electronAPI && window.electronAPI.window) {
    isMaximized.value = await window.electronAPI.window.isMaximized()
  }
}

function handleMinimize() {
  console.log('[App] handleMinimize called', {
    hasAPI: !!window.electronAPI,
    hasWindow: !!window.electronAPI?.window,
    hasMinimize: typeof window.electronAPI?.window?.minimize === 'function',
    electronAPI: window.electronAPI
  })
  
  // 直接检查并调用，如果不存在则等待
  if (window.electronAPI?.window?.minimize) {
    try {
      const result = window.electronAPI.window.minimize()
      console.log('[App] minimize result:', result)
    } catch (error) {
      console.error('[App] Minimize error:', error)
    }
  } else {
    // 如果 API 未就绪，等待后重试
    console.warn('[App] window.electronAPI.window.minimize not available, retrying...')
    setTimeout(() => {
      if (window.electronAPI?.window?.minimize) {
        window.electronAPI.window.minimize()
      } else {
        console.error('[App] window.electronAPI.window.minimize still not available after retry')
      }
    }, 200)
  }
}

function handleMaximize() {
  console.log('[App] handleMaximize called', {
    hasAPI: !!window.electronAPI,
    hasWindow: !!window.electronAPI?.window,
    hasMaximize: typeof window.electronAPI?.window?.maximize === 'function'
  })
  
  if (window.electronAPI?.window?.maximize) {
    try {
      const result = window.electronAPI.window.maximize()
      console.log('[App] maximize result:', result)
      setTimeout(checkMaximized, 100)
    } catch (error) {
      console.error('[App] Maximize error:', error)
    }
  } else {
    console.warn('[App] window.electronAPI.window.maximize not available, retrying...')
    setTimeout(() => {
      if (window.electronAPI?.window?.maximize) {
        window.electronAPI.window.maximize()
        setTimeout(checkMaximized, 100)
      } else {
        console.error('[App] window.electronAPI.window.maximize still not available after retry')
      }
    }, 200)
  }
}

function handleClose() {
  console.log('[App] handleClose called', {
    hasAPI: !!window.electronAPI,
    hasWindow: !!window.electronAPI?.window,
    hasClose: typeof window.electronAPI?.window?.close === 'function'
  })
  
  if (window.electronAPI?.window?.close) {
    try {
      const result = window.electronAPI.window.close()
      console.log('[App] close result:', result)
    } catch (error) {
      console.error('[App] Close error:', error)
    }
  } else {
    console.warn('[App] window.electronAPI.window.close not available, retrying...')
    setTimeout(() => {
      if (window.electronAPI?.window?.close) {
        window.electronAPI.window.close()
      } else {
        console.error('[App] window.electronAPI.window.close still not available after retry')
      }
    }, 200)
  }
}

function showPlayer() {
  showUnlock.value = false
}

function showUnlockView() {
  showUnlock.value = true
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

.app {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
</style>
